package com.demo.com.highavailability.proxy;

import com.demo.com.highavailability.monitor.ThreadMonitor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Proxy;

/**
 * 服务路由代理工厂 - 实现基于线程状态的服务动态路由
 */
@Component
public class ServiceRouterFactory implements ApplicationContextAware {

    private ApplicationContext applicationContext;


    /**
     * 创建支持降级的服务代理
     * @param serviceClass 服务接口类型
     * @param primaryBeanName 主实现Bean名称
     * @param fallbackBeanName 降级实现Bean名称
     * @return 动态代理实例
     */
    @SuppressWarnings("unchecked")
    public <T> T createServiceProxy(Class<T> serviceClass,
                                  String primaryBeanName,
                                  String fallbackBeanName) {
        T primaryService = applicationContext.getBean(primaryBeanName, serviceClass);
        T fallbackService = applicationContext.getBean(fallbackBeanName, serviceClass);

        return (T) Proxy.newProxyInstance(
            serviceClass.getClassLoader(),
            new Class<?>[]{serviceClass},
            (proxy, method, args) -> {
                try {
                    // 检查当前线程状态，决定使用主服务还是降级服务
                    if (ThreadMonitor.isHealthy()) {
                        return method.invoke(primaryService, args);
                    } else {
                        return method.invoke(fallbackService, args);
                    }
                } catch (InvocationTargetException e) {
                    // 异常时自动切换到降级服务
                    return method.invoke(fallbackService, args);
                }
            });
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }
}